const fs = require('fs');
const { promisify } = require('util');
const { exec } = require('child_process');

const write = promisify(fs.writeFile);
const del = promisify(fs.unlink);
const pExec = promisify(exec);

class RunService {
  async runCode(code) {
    const ret = {
      suc: true,
      runInfo: {}
    }
    const curTime = Date.now().toString();
    const fileName = curTime.substring(curTime.length - 6) //以当前时间戳后4位作临时文件的名字
    const fileUrl = `/ns-3-dev/scratch/${fileName}.cc`;
    await write(fileUrl, code).catch((err) => {
      ret.suc = false;
      ret.runInfo = err;
    });
    if (!ret.suc) {
      return ret;
    }
    ret.runInfo.startTime = Date.now();
    const result = await pExec(`cd /ns-3-dev && ./waf --run ${fileName}`, { timeout: 20000}) //写死 20s超时
      .catch((err) => {
        ret.suc = false;
        ret.runInfo = err;
      });
    if (ret.suc) {
      ret.runInfo.endTime = Date.now();
    }
    await del(fileUrl);
    if (!ret.suc) {
      return ret;
    }
    ret.runInfo.stdout = result.stdout;
    ret.runInfo.stderr = result.stderr;
    return ret;
  }
};

module.exports = {
  RunService
};
